<template>
  <div>
    <el-dialog
      class="custom-dialog"
      v-model="dialogVisible"
      :title="title"
      width="500px"
      @close="handleClose"
    >
      <el-form
        class="data-form"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="场景类型" prop="type">
              <el-select
                class="data-input"
                v-model="form.type"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) of dict['scene_type']"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="所属园区" prop="parkId">
              <el-select
                class="data-input"
                v-model="form.parkId"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) of parkOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.pkid"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="设备类型" prop="equipmentType">
              <el-select
                class="data-input"
                v-model="form.equipmentType"
                placeholder="请选择"
                multiple
              >
                <el-option
                  v-for="(item, index) of dict['device_type']"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="场景编号" prop="code">
              <el-input
                class="data-input"
                v-model="form.code"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图标上传">
              <el-upload
                action=""
                :on-change="(file, fileList) => getFile(file, fileList, 'icon')"
                :on-remove="
                  (file, fileList) => handleRemove(file, fileList, 'icon')
                "
                :limit="1"
                accept=".png, .jpg, .jepg"
                list-type="picture-card"
                :auto-upload="false"
                class="custom-upload"
                :file-list="fileList"
              >
                <el-button size="small" type="primary" v-if="!form.icon"
                  ><el-icon><Plus /></el-icon
                ></el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleClose(false)" :loading="loading"
          >取消</el-button
        >
        <el-button type="primary" @click="handleSubmit" :loading="loading"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import VUpload from '@/components/upload/index.vue'
import { parkPageList } from '@/api/manager/dataManage/park'
import { sceneAdd, sceneDetail } from '@/api/manager/dataManage/deviceManage.js'
import { useDict } from '@/hooks/useDict'
import { Plus } from '@element-plus/icons-vue'
const { dict, getDictValue } = useDict(['scene_type', 'device_type'])
defineOptions({
  name: 'AddDialog',
})
const props = defineProps({
  detail: {
    type: Object,
  },
})
watch(
  () => props.detail,
  () => {
    if (props.detail.pkid && dialogVisible.value) {
      handleDetail()
    } else {
      form.value.parkId = props.detail.parkId || ''
    }
  },
)
const emit = defineEmits(['close'])
const title = ref('')
const dialogVisible = ref(false)
const handleClose = (isFlash) => {
  form.value = {
    equipmentType: [],
  }
  formRef.value.clearValidate()
  dialogVisible.value = false
  emit('close', isFlash)
}
const formRef = ref(null)
const form = ref({
  equipmentType: [],
})
const fileList = ref([])
const rules = ref({
  type: [{ required: true, message: '请选择场景类型', trigger: 'blur' }],
  parkId: [{ required: true, message: '请选择所属园区', trigger: 'blur' }],
  equipmentType: [
    { required: true, message: '请选择设备类型', trigger: 'blur' },
  ],
})
const loading = ref(false)
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      const params = JSON.parse(JSON.stringify(form.value))
      // 处理设备类型
      params.equipmentType =
        params.equipmentType.length > 0 ? params.equipmentType.join(',') : ''
      try {
        let res = await sceneAdd(params)
        if (res.success) {
          ElMessage.success('保存成功')
          handleClose(true)
        } else {
          ElMessage.error(res.message)
        }
        loading.value = false
      } catch (error) {
        console.log('error', error)
        loading.value = false
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}
const handleDetail = async () => {
  form.value = {
    ...props.detail,
    equipmentType: props.detail.equipmentType.split(','),
  }
  if (props.detail.icon) {
    fileList.value = [
      {
        name: 'name',
        uid: '1',
        url: props.detail.icon,
      },
    ]
  }
  // const res = await sceneDetail(props.detail.pkid)
  // form.value = res.data
}
const parkOptions = ref([])
const initParkList = async () => {
  const res = await parkPageList({ pageIndex: 1, pageSize: 9999, enable: '1' })
  parkOptions.value = res.data.list
}

const getFile = (file, fileList, key) => {
  getBase64(file.raw).then((res) => {
    form.value[key] = res
  })
}
const getBase64 = (file) => {
  return new Promise(function (resolve, reject) {
    let reader = new FileReader()
    let imgResult = ''
    reader.readAsDataURL(file)
    reader.onload = function () {
      imgResult = reader.result
    }
    reader.onerror = function (error) {
      reject(error)
    }
    reader.onloadend = function () {
      resolve(imgResult)
    }
  })
}
const handleRemove = (file, fileList, key) => {
  if (file) {
    form.value[key] = ''
  }
}

watch(
  () => dialogVisible.value,
  () => {
    if (dialogVisible.value) {
      initParkList()
    }
  },
)
defineExpose({ dialogVisible, title })
</script>
<style lang="scss" scoped>
:deep(.custom-upload) {
  .el-upload--picture-card {
    width: 100px;
    height: 100px;
    border: none;
    background: transparent;
  }
  .el-upload-list__item {
    width: 100px;
    height: 100px;
  }
  .el-button {
    width: 100px;
    height: 100px;
    background: #fafafa;
    color: #409eff;
    border: 1px dashed #cdd0d6;
    border-radius: 6px;
    .el-icon {
      font-size: 20px;
    }
  }
}
</style>
